<template>
  <el-button :type="type" :loading="loading" :plain="plain" :icon="icon" :disabled="disabled"
             @click="buttonClick($event)">
    <span style="display: flex;justify-content: center;align-items: center">
      <slot></slot>
    <span v-if="time" style="margin-left: 4px">({{ time }})</span>
    </span>
  </el-button>
</template>

<script>
export default {
  name: 'index',
  props: {
    type: {
      type: String
    },
    plain: {
      type: Boolean
    },
    loading: {
      type: Boolean,
      default: false
    },
    icon: {
      type: String
    },
    interval: {
      type: Number,
      default: 0
    },
    auto: {
      type: Boolean,
      default: false
    },
    isDisabled: {
      type: Boolean,
      default: false
    }
  },
  watch: {
    isDisabled(val) {
      if(!val && this.time === 0) {
        this.disabled = false
      }
    }
  },
  data() {
    return {
      instance: null,
      disabled: false,
      time: 0
    }
  },
  methods: {
    buttonClick(e) {
      this.$emit('click', e)
      if (this.auto) this.start()
    },
    start() {
      if (typeof this.interval === 'number' && this.interval) {
        this.time = this.interval
        this.disabled = true
        this.startInterval()
      } else {
        this.disabled = false
      }
    },
    startInterval() {
      this.instance = setInterval(() => {
        if (this.time) this.time--
        if (this.time === 0) {
          this.disabled = this.isDisabled
          this.clearInterval()
        }
      }, 1000)
    },
    clearInterval() {
      if (this.instance) {
        clearInterval(this.instance)
        this.instance = null
      }
    }
  },
  beforeDestroy() {
    this.clearInterval()
  }
}
</script>

<style scoped lang="scss">

</style>
